package com.ysu.zyw.demo5;

import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * Created by ZeRur on 2016/1/9.
 * @author yaowu.zhang
 */
public class PersonValidator implements ConstraintValidator<ValidPerson, Person5> {

    @Override
    public void initialize(ValidPerson constraintAnnotation) {
    }

    @Override
    public boolean isValid(Person5 value, ConstraintValidatorContext context) {
        if(value == null) {
            return true;
        }
        if(!StringUtils.hasText(value.getPassword())) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("${validatedValue}密码不能为空").addPropertyNode("password").addConstraintViolation();
            return false;
        }
        if(!StringUtils.hasText(value.getPasswordConfirm())) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("${validatedValue}密码不能为空").addPropertyNode("passwordConfirm").addConstraintViolation();
            return false;
        }
        if(!ObjectUtils.nullSafeEquals(value.getPassword(), value.getPasswordConfirm())) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("密码和确认密码不相同").addPropertyNode("passwordConfirm").addPropertyNode("password").addConstraintViolation();
            return false;
        }
        return true;
    }

}
